<?php

namespace app\store\controller;

use app\store\model\User as UserModel;
use app\store\model\user\Grade as GradeModel;
use \think\Db;
/**
 * 用户管理
 * Class User
 * @package app\store\controller
 */
class User extends Controller
{
    /**
     * 用户列表
     * @param string $nickName 昵称
     * @param int $gender 性别
     * @param int $grade 会员等级
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index($nickName = '', $gender = null, $grade = null, $UID = 0, $sxkeyword='', $minmoney=0)
    {
        $model = new UserModel;
        $list = $model->getList($nickName, $gender, $grade, $UID, $sxkeyword, $minmoney);
        // 会员等级列表
        $gradeList = GradeModel::getUsableList();
        return $this->fetch('index', compact('list', 'gradeList'));
    }

		// mmmodify 新增线下用户
		public function add(){
			if (!$this->request->isAjax()) {
			    return $this->fetch('add');
			}
			$postArr = $this->postData('grade');

			$model = new UserModel;

			$postArr['nickName'] = $postArr['true_name'];
			$postArr['wxapp_id'] = $this->getWxappId();
			$postArr['create_time'] = time();
			$postArr['update_time'] = time();
			$res = Db::name('user')->insert($postArr);
			if($res){
				return $this->renderSuccess('线下用户添加成功', url('user/index'));
			}
			return $this->renderError($model->getError() ?: '线下用户添加失败');
		}
		// 给用户赠送商品或者赠送项目
		public function giftgoods(){
			$postArr = $this->postData('giftgoods');
			if($postArr['goods_id']>0){
				$userId = $this->postData('user_id')[0];
				$giftGoodid = $postArr['goods_id'];
				$giftGoodid2 = $postArr['goods_id2'];
				if($giftGoodid != $giftGoodid2){
					return $this->renderError('两次输入的商品或项目ID不一致，请重新输入');
				}
				else{
					// 判断是免费赠送还是新增消费
					$send_buy = $postArr['send_buy'];
					// return $this->renderError('执行到这里'.$send_buy);
					// 检查非商品的项目是否存在
					$goodObj = Db::name('goods')->where(['goods_id'=>$giftGoodid, 'cons_type'=>20])->find();
					$goodObjSku = Db::name('goods_sku')->where(['goods_id'=>$giftGoodid])->find();
					if($goodObjSku['stock_num']==0){
						return $this->renderError('该项目库存为0，无法赠送或新增');
					}
					if(isset($goodObj['goods_id']) && $goodObj['goods_id']>0){
						// 查找此用户是否已经赠送了该项目且未消费完
						$sql = "select bb.cons_lastnum,bb.cons_num from zj_order_goods as aa left join zj_order as bb on aa.order_id=bb.order_id 
						where aa.user_id=$userId and aa.goods_id=$giftGoodid and bb.cons_lastnum>0";
						$orderRes = Db::query($sql);
						if(count($orderRes)>0){
							return $this->renderError('已赠送该项目且未核销完，请勿重复赠送项目');
						}
						else{
							// 开始赠送
							// 此处应当用到数据库事务
							$skuidObj = Db::name('goods_sku')->where(['goods_id'=>$giftGoodid])->find();
							$imgeObj = Db::name('goods_image')->where(['goods_id'=>$giftGoodid])->find();
							$goodObj['goods_sku'] = $skuidObj;
							$goodObj['image'] = $imgeObj;

							$user['user_id'] = $userId;
							//赠送项目入库逻辑
							$this->giftGoodFun($user, $goodObj, $this->getWxappId(), $send_buy);
							//新增消费入库分销逻辑
							return $this->renderSuccess('操作成功');
						}
					}
					else{
						return $this->renderError('项目不存在或该ID不是项目ID');
					}
				}
			}
			else{
				return $this->renderError('请输入要赠送的商品和项目ID');
			}
		}

    /**
     * 删除用户
     * @param $user_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($user_id)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($model->setDelete()) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError($model->getError() ?: '删除失败');
    }

    /**
     * 用户充值
     * @param $user_id
     * @param int $source 充值类型
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function recharge($user_id, $source)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($model->recharge($this->store['user']['user_name'], $source, $this->postData('recharge'))) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 修改会员等级
     * @param $user_id
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function grade($user_id)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($model->updateGrade($this->postData('grade'))) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

	public function userInfo($user_id)
	{
		$model = UserModel::detail($user_id);
		return $model;
	}

	private function giftGoodFun($user, $goodObj, $wxappid, $send_buy=1){
		// 订单商品总数量
		$orderTotalNum = 1;

		$allPayMoney = $goodObj['goods_sku']['goods_price'] * $orderTotalNum;

		$shopObj = Db::name('store_shop')->where(['wxapp_id'=>$wxappid])->find();
		$shopid = $shopObj['shop_id'];

		$userid = $user['user_id'];

		// 订单数据入库，不使用积分和优惠券，mmmodify
		$data = [
		    'user_id' => $user['user_id'],
		    'order_no' => date("Ymd").rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(1,9),
		    'total_price' => $allPayMoney,
		    'order_price' => $allPayMoney,

			'cons_type' => $goodObj['cons_type'],	// mmmodify
			'cons_num' => $goodObj['cons_num'],
		    'cons_lastnum' => $goodObj['cons_num'],

			'coupon_id' => 0,
		    'coupon_money' => 0.00,
		    'points_money' => 0.00,
		    'points_num' => 0,
		    'pay_price' => $allPayMoney,
		    'delivery_type' => 20,  // 线下消费自提
		    'pay_type' => 20,	// 微信支付
		    'buyer_remark' => '充值赠送',
		    'order_source' => 10,	// 普通订单
		    'order_source_id' => 0,	// 订单来源统一为0
		    'points_bonus' => 0,
		    'wxapp_id' => $wxappid,
			'create_time'=>time(),
			'update_time'=>time()
		];
		$data['pay_status'] = 20; //直接设置支付成功
		$data['pay_time'] = time();
		$data['transaction_id'] = '111222333';
		$data['express_price'] = 0;	// 运费金额
		$data['extract_shop_id'] = $shopid;

		// 保存订单记录
		$orderID = Db::name('order')->insertGetId($data);
		// 保存后获取保存的订单号

		// 订单拓展入库，消费记录，账户余额等等

		// 记录自提信息
		$linkObj = Db::name('user')->where('user_id', $userid)->find();
		Db::name('order_extract')->insert([
		    'linkman' => isset($linkObj['true_name']) ? $linkObj['true_name'] : '赠送',
		    'phone' => isset($linkObj['true_mobile']) ? $linkObj['true_mobile'] : '13888888888',
		    'user_id' => $userid,
		    'wxapp_id' => $wxappid,
			'order_id' => $orderID,
			'create_time'=>time(),
		]);

		// 订单中商品信息入库
		$item = [
		    'user_id' => $user['user_id'],
		    'wxapp_id' => $wxappid,
		    'goods_id' => $goodObj['goods_id'],
		    'goods_name' => $goodObj['goods_name'],
			'deduct_stock_type' => $goodObj['deduct_stock_type'],

		    'image_id' => $goodObj['image']['image_id'],

		    'spec_type' => $goodObj['spec_type'],
		    'spec_sku_id' => $goodObj['goods_sku']['spec_sku_id'],
		    'goods_sku_id' => $goodObj['goods_sku']['goods_sku_id'],
		    'goods_attr' => '',
		    'content' => $goodObj['content'],
		    'goods_no' => $goodObj['goods_sku']['goods_no'],
		    'goods_price' => $goodObj['goods_sku']['goods_price'],
		    'line_price' => $goodObj['goods_sku']['line_price'],
		    'goods_weight' => $goodObj['goods_sku']['goods_weight'],
		    'is_user_grade' => 0,	// 是否存在会员折扣
		    'grade_ratio' => 0,
		    'grade_goods_price' => 0.00,
		    'grade_total_money' => 0.00,
		    'coupon_money' => 0.00,
		    'points_money' => 0.00,
		    'points_num' => 0,
		    'points_bonus' => 0,
		    'total_num' => $orderTotalNum,
		    'total_price' => $allPayMoney,
		    'total_pay_price' => $allPayMoney,
		    'is_ind_dealer' => 0,	// 是否开启分销
		    'dealer_money_type' => 10,	// 返利模式，10百分比，20固定金额
		    'first_money' => 0.00,
		    'second_money' => 0.00,
		    'third_money' => 0.00,
			'order_id' => $orderID,
			'create_time' => time()
		];
		$res2 = Db::name('order_goods')->insert($item);
		// echo '<pre>'; print_r($res2); exit;

		// 更新商品库存信息
		Db::name('goods')->where('goods_id',$goodObj['goods_id'])->setInc('sales_actual', 1);
		$upDD['goods_sales'] = $goodObj['goods_sku']['goods_sales']+1;
		$upDD['stock_num'] = $goodObj['goods_sku']['stock_num']-1;
		// echo '<pre>'; print_r($goodObj['goods_sku']); exit;
		$goods_sku_id = $goodObj['goods_sku']['goods_sku_id'];
		Db::name('goods_sku')->where('goods_sku_id',$goods_sku_id)->update($upDD);
	}

	public function settags($user_id,$tags_id){

		$tags_id = implode(',',$tags_id);

		$name = Db::name('tags_list')->where('id','in',$tags_id)->column('name');
		$data = [
			'tags_ids'=>$tags_id,
			'tags'=>implode(',',$name),
		];
		$r = Db::name('user')->where('user_id',$user_id)->update($data);

		if ($r !== false) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError('操作失败');
	}
	/*
	 * 核销记录
	 * */
	public function getWriteList(){
        $order_id = $this->postData('order_id');
        $data = Db::name('store_shop_order')->alias('a')->join('store_shop_clerk b','a.clerk_id = b.clerk_id')->where('order_id', $order_id['0'])->select()->toArray();

        foreach($data as $k=>$v){
            $data[$k]['new_update_time'] = date('Y-m-d H:i:s',$v['update_time']);
        }
        if ($data !== false) {
            return json_encode([
                'code' => 0,
                'data' => $data
            ]);
        }
        return json_encode([
            'code' => 1,
            'msg' => '暂无数据'
        ]);
    }
}
